// Created by lorin
// 2024/09/19 11:23 AM

using System;
using System.IO;
using Build;
using Newtonsoft.Json;
using UnityEditor;
using UnityEditor.AddressableAssets;
using UnityEditor.AddressableAssets.Settings;
using UnityEngine;
using UnityEngine.AddressableAssets;

namespace Editor
{
    public enum VersionType
    {
        Apk, // 打包apk
        Patch, // 打包补丁包
    }

    public struct VersionInfo
    {
        public string newestVersion; // 最新app版本
        public string patchVersion; // 补丁包版本
        public string minVersion; // 支持的最低app版本
        public bool forceUpdateApk; // 低于最低版本时强制更新
    }
    
    public class VMWindow : EditorWindow
    {
        private VersionType m_VersionType;
        private string m_VersionName;
        private int m_VersionCode;
        private string m_MinVersionName;
        private bool m_ForceUpdateApk;


        [MenuItem("EFrame Tools/Res Vm")]
        static void ShowWindow()
        {
            var window = GetWindow<VMWindow>();
            window.minSize = new Vector2(400, 500);
        }
        
        VMWindow()
        {
            titleContent = new GUIContent("资源版本管理");
        }

        private void OnGUI()
        {
            GUILayout.Space(10);
            var totalStyle = new GUIStyle();
            totalStyle.padding = new RectOffset(70, 70, 0, 0);
            totalStyle.fixedWidth = 300;
            GUILayout.BeginVertical(totalStyle);
            var centeredStyle = GUI.skin.GetStyle("Label");
            centeredStyle.alignment = TextAnchor.MiddleCenter;
            centeredStyle.fontStyle = FontStyle.Bold;
            GUILayout.Label("---------- 版本信息 ----------", centeredStyle);
            GUILayout.Space(10);
            m_VersionType = (VersionType)EditorGUILayout.EnumPopup("打包类型:", m_VersionType, GUILayout.Width(260));
            GUILayout.Space(10);
            if (m_VersionType == VersionType.Apk) // apk类型需要编辑版本名及版本号
            {
                m_VersionName = EditorGUILayout.TextField("版本名:", m_VersionName, GUILayout.Height(20), GUILayout.Width(260));
                // m_VersionCode = EditorGUILayout.IntField("版本号:", m_VersionCode, GUILayout.Height(20), GUILayout.Width(260));   
                m_VersionCode = PlayerSettings.Android.bundleVersionCode + 1;
            }
            else // patch类型不可编辑版本名及版本号
            {
                m_VersionName = PlayerSettings.bundleVersion;
                m_VersionCode = PlayerSettings.Android.bundleVersionCode;
                EditorGUILayout.LabelField("版本名:", m_VersionName, GUILayout.Height(20), GUILayout.Width(260));
            }
            EditorGUILayout.LabelField("版本号:", m_VersionCode.ToString(), GUILayout.Height(20), GUILayout.Width(260));
            GUILayout.Space(10);
            m_MinVersionName = EditorGUILayout.TextField("支持的最低Apk版本:", m_MinVersionName, GUILayout.Height(20), GUILayout.Width(260));
            GUILayout.Space(10);
            m_ForceUpdateApk = EditorGUILayout.Toggle("低于最低版本时强制更新?:", m_ForceUpdateApk);
            
            GUILayout.Space(30);
            if (GUILayout.Button("Ok", GUILayout.Height(30)))
            {
                OnOkClick();
            }

            GUILayout.EndVertical();
        }

        private void OnOkClick()
        {
            // 1. 生成版本配置文件
            // 2. build资源bundle包
            // 3. 上传资源包到服务器
            var info = new VersionInfo
            {
                newestVersion = m_VersionName,
                patchVersion = "",
                minVersion = m_MinVersionName,
                forceUpdateApk = m_ForceUpdateApk
            };

            var versionFileName = "app.version";
            var versionPath = Path.Combine(Environment.CurrentDirectory, "ExternalData", PlatformMappingService.GetPlatformPathSubFolder(), versionFileName);
            File.WriteAllText(versionPath, JsonConvert.SerializeObject(info));
            var settings = AddressableAssetSettingsDefaultObject.Settings;
            if (m_VersionType == VersionType.Apk) // 发布新版本
            {
                PlayerSettings.bundleVersion = m_VersionName;
                PlayerSettings.Android.bundleVersionCode = m_VersionCode;
                var resPath = Path.Combine(Application.dataPath, "Resources", versionFileName); // 同时将版本文件放入包中
                File.WriteAllText(resPath, JsonConvert.SerializeObject(info));
                settings.ActivePlayerDataBuilderIndex = 3; // RemoteBuiltInPackedMode
                var profile = settings.profileSettings.GetProfileDataById("Default");
                // settings.profileSettings.S
            }
            else // 发布热更包
            {
                settings.ActivePlayerDataBuilderIndex = 4; // HotUpdatePackedMode
            }
            
            AddressableAssetSettings.BuildPlayerContent(out var result); // 打包资源
            if (string.IsNullOrEmpty(result.Error))
            {
                Debug.Log($"--->>> Build Success!");
            }

            var options = new BuildPlayerOptions();
            // var playerSetting = BuildPlayerWindow.DefaultBuildMethods.GetBuildPlayerOptions(options);
            // BuildPipeline.BuildPlayer(playerSetting); // 打包apk
        }
    }
}